import {
  userPageApi,
  addUserApi,
  editUserApi,
  delUserApi,
  orgAllByOrgTypeApi,
  userRoleApi,
  editUserRoleApi,
  editUserPasswordApi,
  getUserInfoApi
} from '@/api/system/user'
import { roleListApi } from '@/api/system/role'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'

type props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  drawerShow: Ref<boolean>
  userForm: Ref<{ [index: string]: any }>
  proTableInst: Ref<ProTableInst | null>
  orgOptions: Ref<any[]>
  roleOptions: Ref<any[]>
  currentUserRole: Ref<any[]>
}

export const useUserApi = ({
  handleType,
  handleTag,
  drawerShow,
  userForm,
  proTableInst,
  orgOptions,
  roleOptions,
  currentUserRole
}: props) => {
  const confirmLoading = ref(false)
  const editRoleModalLoading = ref(false)
  const userStatusLoading = ref(false)
  const updatePwdModalLoading = ref(false)

  // 获取用户列表
  const fetchUserPage = async (pageRequest, queryParams) => {
    try {
      const res = await userPageApi({
        ...queryParams,
        pageRequest
      })

      if (res.code === '0000') {
        return {
          data: res.data?.content,
          total: res.data?.total
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增or修改用户
  const fetchAddOrEditUser = async () => {
    try {
      confirmLoading.value = true
      const fetch = handleType.value === 'add' ? addUserApi : editUserApi
      const data = {
        ...userForm.value,
        orgName: useDictDisplay(orgOptions.value, userForm.value.orgId)
      }
      if (data.__displayValue__) delete data.__displayValue__
      const res = await fetch(data)
      if (res.code === '0000') {
        window['$message'].success(handleTag.value + '成功')
        proTableInst.value?.reload()
        drawerShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除用户
  const fetchDelUser = async (id) => {
    try {
      const res = await delUserApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 改变用户状态
  const changeUserStatus = async (row) => {
    userStatusLoading.value = true
    const res = await editUserApi({
      ...row,
      enabled: !row.enabled
    })

    if (res.code == '0000') {
      useMsg('success', '修改成功')
      proTableInst.value?.staticReload()
    }

    userStatusLoading.value = false
  }

  // 获取机构数据
  const fetchOrgList = async () => {
    const res = await orgAllByOrgTypeApi()
    if (res.code === '0000') {
      orgOptions.value = res.data
    }
  }

  // 获取全部角色
  const fetchRoleList = async () => {
    const res = await roleListApi()
    if (res.code === '0000') {
      roleOptions.value = res.data
    }
  }

  // 获取用户的角色列表
  const fetchUserRoleList = async (id) => {
    editRoleModalLoading.value
    const res = await userRoleApi({
      id
    })
    if (res.code === '0000' && res.data) {
      currentUserRole.value = res.code
    }
    editRoleModalLoading.value = false
  }

  // 保存角色编辑
  const fetchEditUserRole = async ({ id, roleCode }, cb: () => void) => {
    editRoleModalLoading.value
    const res = await editUserRoleApi({ userId: id, roleCode })
    if (res.code === '0000') {
      useMsg('success', '授予角色成功')
      cb()
      proTableInst.value?.reload()
    }
    editRoleModalLoading.value = false
  }

  // 修改用户密码
  const fetchEditUserPassword = async ({ id, password }, cb: () => void) => {
    updatePwdModalLoading.value = true
    const res = await editUserPasswordApi({ id, password })
    if (res.code === '0000') {
      useMsg('success', '密码修改成功')
      cb()
    }
    updatePwdModalLoading.value = false
  }

  fetchRoleList()

  return {
    fetchUserPage,
    fetchAddOrEditUser,
    fetchDelUser,
    changeUserStatus,
    fetchUserRoleList,
    fetchEditUserRole,
    fetchEditUserPassword,
    editRoleModalLoading,
    userStatusLoading,
    updatePwdModalLoading
  }
}
